import axios from "axios";
import { ElLoading } from "element-plus";

let loading = null;

const http = axios.create({
  baseURL: "",
  timeout: 60000,
  headers: {
    "Content-type": "application/json",
  },
});
// 单例模式
http.interceptors.request.use(
  (config) => {
    if (!loading) {
      loading = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    }

    let token = localStorage.getItem("userinfo");
    if (token) {
      token = JSON.parse(token);
      const { token_type, access_token } = token;
      config.headers["Blade-Auth"] = `${token_type} ${access_token}`;
      return config;
    }
    config.headers["Authorization"] = `Basic c2FiZXI6c2FiZXJfc2VjcmV0`;
    return config;
  },
  (err) => {
    if (loading) {
      loading.close();
      loading = null;
    }
    // return Promise.reject(err);
    throw new Error("请求失败了");
  }
);

http.interceptors.response.use(
  ({ data, code }) => {
    if (loading) {
      loading.close();
      loading = null;
    }
    /* const codeObj = {
        200(){
            return data
        },
        304(){
            return Promise.reject('永久重定向')
        },
        404(){
            return Promise.reject('没有资源')
        },
        undefined(){
            return data
        }
    }
    codeObj[code]() */
    return data;
  },
  (err) => {
    if (loading) {
      loading.close();
      loading = null;
    }
    throw new Error("请求失败了");
  }
);

export const get = (url, params) => {
  return http.get(url, { params });
};

export const post = (url, data) => {
  return http.post(url, { data });
};

export default http;
